package comm;

import gui.ClientWindow;
import structures.City;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import java.io.IOException;
import java.io.StringReader;
import java.net.URL;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created with IntelliJ IDEA.
 * User: dna
 * Date: 27.04.13
 * Time: 16:15
 */
public class InputTask {

    private ClientWindow cw;
    private Map<String, City> cities;
    private EZConnection conn;
    private Timer timer;
    private ClientWindow gui;

    public InputTask(Map<String, City> cities, URL url, ClientWindow gui) throws IOException{

        this.cities = cities;
        this.gui = gui;

        conn = new EZConnection(url);

        timer = new Timer();
        timer.schedule(new UpdateTask(), 2 * 1000);
    }

    public void setCw(ClientWindow cw) {
        this.cw = cw;
    }

    class UpdateTask extends TimerTask {

        @Override
        public void run() {
            try {
                conn.open();
                conn.setMethod(EZConnection.Method.GET);
                String content = conn.getContent();
                conn.close();

                // XML stream reader
                StringReader sr = new StringReader(content);
                InputSource is = new InputSource(sr);

                DocumentBuilderFactory docBuilderFact = DocumentBuilderFactory.newInstance();
                DocumentBuilder docBuilder = docBuilderFact.newDocumentBuilder();

                // New DOM document
                Document doc = docBuilder.parse(is);

                NodeList l1 = doc.getElementsByTagName("State");

                City temp;
                boolean add;

                for (int i=0; i<l1.getLength(); i++){
                    Element e1 = (Element) l1.item(i);
                    NodeList l2 = e1.getElementsByTagName("Name");

                    if (l2.item(0).getTextContent().equals("Key") || l2.item(0).getTextContent().equals("UpdateTime")){
                        continue;
                    }

                    add = false;
                    temp = cities.get(l2.item(0).getTextContent());
                    if (temp == null){
                        add = true;
                        temp = new City();

                        if (l2.item(0).getTextContent().contains(";")){
                            temp.setByWhat("Coordinates");
                        } else if (l2.item(0).getTextContent().contains(".")) {
                            temp.setByWhat("Ip");
                        } else {
                            temp.setByWhat("Name");
                        }
                    }

                    for (int j=0; j<l2.getLength(); j++){
                        Element e2 = (Element) l2.item(j);
                        temp.setName(e2.getTextContent());
                    }

                    NodeList l3 = e1.getElementsByTagName("Value");

                    for (int j=0; j<l3.getLength(); j++){
                        Element e2 = (Element) l3.item(j);
                        NodeList l4 = e2.getChildNodes();

                        for (int k=0; k<l4.getLength(); k++){
                            Element e3 = (Element) l4.item(k);
                            temp.setParameter(e3.getTagName(), e3.getTextContent());
                        }
                    }

                    if (add){
                        cities.put(temp.getName(),temp);
                    }
                }

                gui.updateCityList();
                gui.setMessage("Update list.");

            } catch (IOException e) {
                if (cw != null)
                    cw.setMessage("<html><span style=\"color: red\">Server not responding!</span></html>");
            } catch (ParserConfigurationException e) {
                if (cw != null)
                    cw.setMessage("<html><span style=\"color: red\">Server not responding!</span></html>");
            } catch (SAXException e) {
                if (cw != null)
                    cw.setMessage("<html><span style=\"color: red\">Server not responding!</span></html>");
            }

            timer.schedule(new UpdateTask(), 5 * 1000);
        }
    }
}
